package com.yanyu.space.sys.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yanyu.space.common.core.bean.web.R;
import com.yanyu.space.sys.bean.enums.SysRCode;
import com.yanyu.space.sys.bean.po.User;
import com.yanyu.space.sys.bean.vo.user.UserInfoVo;
import com.yanyu.space.sys.bean.vo.user.UserProfileAvatarVo;
import com.yanyu.space.sys.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author yanyu
 */
@AllArgsConstructor
@Api(tags = "系统用户")
@RestController
@RequestMapping("/sys/user/profile")
@Validated
public class UserProfileController {

    private IUserService userService;

    @GetMapping
    @ApiOperation(value = "查询用户信息")
    public R profile() {
        Long userId = StpUtil.getLoginIdAsLong();
        UserInfoVo user = userService.getById(userId);
        return R.ok(user);
    }

    @PutMapping
    @ApiOperation(value = "修改用户信息")
    public R updateprofile(@RequestBody User user) {
        userService.updateById(user);
        return R.ok(user);
    }

    @PutMapping("updatePwd")
    public R updatePwd(@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword) {
        Long userId = StpUtil.getLoginIdAsLong();
        User user = userService.getById(userId);
        if (StringUtils.equalsIgnoreCase(oldPassword, newPassword)) {
            return R.fail(SysRCode.PASSWORD_CHANGE_SOME);
        } else if (user != null) {
            if (user.getPassword().equals(oldPassword)) {
                userService.update(Wrappers.<User>lambdaUpdate().eq(User::getId, userId).set(User::getPassword, newPassword));
            }
        }
        return R.ok();
    }

    @PostMapping("avatar")
    @ApiOperation(value = "添加用户头像信息")
    public R avatar(@RequestParam("avatarfile") MultipartFile file) {
        userService.avatar(file);
        return R.ok();
    }
}
